package com.sz.common.pay.pingan.core.client;

import com.sz.common.pay.common.InitPrint;
import com.sz.common.pay.common.PayLogger;
import com.sz.common.pay.common.PaymentMethods;
import com.sz.common.pay.pingan.constant.Constant;
import com.sz.common.pay.pingan.exception.NoAvailableConnectException;
import com.sz.common.pay.pingan.util.ConnectUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Function: 解决性能 计数器 <br>
 * @author: siqishangshu <br>
 * @date: 2017-10-31 16:02:00
 */
public class ConnectionPoolFactory {
    private static List<Connection> connections = new ArrayList<>();
    private static PayLogger payLogger = PayLogger.getLogger(ConnectionPoolFactory.class);

    static {
        init();
    }

    private static void init() {
        if (PaymentMethods.isSupport(PaymentMethods.PINGAN)) {
            int perMax = (int) (Constant.MAX_USEAGE * Constant.MAX_CONN);
            for (Object o : Constant.HOSTS) {
                String[] arr = o.toString().split(Constant.IP_PORT_SPILT);
                if (!ConnectUtil.reachableConnection(new Connection(arr[0], Integer.parseInt(arr[1])))) {
                    payLogger.info("支付配置", arr[0] + ":" + arr[1] + "状态不可达");
                    break;
                }
                for (int l = 0; l < perMax; l++) {
                    Connection conn = new Connection(arr[0], Integer.parseInt(arr[1]));
                    connections.add(conn);
                }
            }
            InitPrint.print();
            if (connections.isEmpty()) {
                payLogger.info("支付配置", "没有可用的支付链接");
            } else {
                payLogger.info("支付配置", "当前可用的支付链接数［" + connections.size() + "］");
            }
        }
    }

    public static synchronized Connection getConnection() throws NoAvailableConnectException {
        CountConnections();
        for (Connection connection : connections) {
            if (connection.isUnLock()) {
                connection.lock();
                return connection;
            }
        }
        throw new NoAvailableConnectException("There is not enough B2BiC server");
    }

    private static void CountConnections() {
        int size = 0;
        for (Connection connection : connections) {
            if (connection.isUnLock()) {
                size++;
            }
        }
        payLogger.info("支付配置", "当前可用的支付链接数 ［" + size + "］");
        if (connections.isEmpty()) {
            payLogger.info("支付配置", "重新尝试初始化链接");
            init();
        }
    }
}
